package com.timebank.score.service.impl;

import com.timebank.common.core.constant.SecurityConstants;
import com.timebank.common.core.exception.ServiceException;
import com.timebank.common.core.result.Result;
import com.timebank.common.core.web.pojo.AjaxResult;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.score.mapper.ScoreTaskLogMapper;
import com.timebank.score.mapper.ScoreTaskMapper;
import com.timebank.score.pojo.entity.ScoreTask;
import com.timebank.score.pojo.entity.ScoreTaskLog;
import com.timebank.score.pojo.vo.ScoreTaskVO;
import com.timebank.score.service.ScoreTaskService;
import com.timebank.system.model.LoginUser;
import com.timebank.system.pojo.SysUser;
import com.timebank.system.service.RemoteUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 积分任务 实现类
 * @author shiliuyinzhen
 */
@Service
public class ScoreTaskServiceImpl implements ScoreTaskService {

    @Resource
    private ScoreTaskMapper scoreTaskMapper;

    @Resource
    private ScoreTaskLogMapper scoreTaskLogMapper;

    @Resource
    private RemoteUserService remoteUserService;

    /**
     * 新增积分任务
     * @param scoreTask
     * @return
     */
    @Override
    public AjaxResult addScoreTask(ScoreTask scoreTask) {
        //检查任务是否存在
        checkTaskExist(scoreTask);
        scoreTask.setCreateBy(SecurityUtils.getUsername());
        scoreTask.setCreateTime(LocalDateTime.now());
        scoreTask.setRemark("新增积分任务");
        return scoreTaskMapper.addScoreTask(scoreTask) > 0 ?
                AjaxResult.success("新增积分任务成功") : AjaxResult.error("新增积分任务失败");
    }

    /**
     * 查询积分任务是否存在
     * @param scoreTask
     * @return
     */
    private void checkTaskExist(ScoreTask scoreTask) {
        ScoreTask scoreTask1 = new ScoreTask();
        scoreTask1.setTitle(scoreTask.getTitle());
        ScoreTask scoreTask2 = scoreTaskMapper.getScoreTask(scoreTask1);
        if (scoreTask2 != null){
            throw new ServiceException(scoreTask.getTitle() + "已经存在");
        }
    }

    /**
     * 修改积分任务
     * @param scoreTask
     * @return
     */
    @Override
    public AjaxResult updateScoreTask(ScoreTask scoreTask) {
        //检查任务是否存在
        checkTaskExist(scoreTask);
        scoreTask.setUpdateBy(SecurityUtils.getUsername());
        scoreTask.setUpdateTime(LocalDateTime.now());
        scoreTask.setRemark("修改积分任务");
        return scoreTaskMapper.updateScoreTask(scoreTask) > 0 ?
                AjaxResult.success("修改积分任务成功") : AjaxResult.error("修改积分任务失败");
    }

    /**
     * 查询积分任务列表
     *
     * @param scoreTask
     * @return
     */
    @Override
    public List<ScoreTaskVO> getScoreTaskList(ScoreTask scoreTask) {
        List<ScoreTaskVO> list = scoreTaskMapper.getScoreTaskList(scoreTask);
        String token = SecurityUtils.getToken();
        Long userId = SecurityUtils.getUserId();
        //如果已登录
        for (ScoreTaskVO scoreTaskVO : list) {
            //初始化为false
            scoreTaskVO.setTaskStatus(false);
            scoreTaskVO.setReceiveStatus(false);
            if (token != null && token != "" && userId > 0){
                //查询任务记录
                ScoreTaskLog scoreTaskLog = ScoreTaskLog.builder()
                        .taskId(scoreTaskVO.getId())
                        .userId(SecurityUtils.getUserId())
                        .build();
                ScoreTaskLog scoreTaskLog1 = scoreTaskLogMapper.getScoreTaskLog(scoreTaskLog);
                //如果存在
                if (scoreTaskLog1 != null) {
                    LocalDateTime beginTime = LocalDateTime.now().with(LocalTime.MIN);
                    LocalDateTime endTime = LocalDateTime.now().with(LocalTime.MAX);
                    //查询是否已完成
                    LocalDateTime finishTime = scoreTaskLog1.getFinishTime();
                    if (finishTime != null) {
                        //如果今天已完成，设置为true
                        if (finishTime.isAfter(beginTime)
                                && finishTime.isBefore(endTime)) {
                            scoreTaskVO.setTaskStatus(true);
                        }
                    }
                    //查询奖励是否已经领取
                    LocalDateTime receiveTime = scoreTaskLog1.getReceiveTime();
                    if (receiveTime != null){
                        //如果今天已领取，设置为true
                        if (receiveTime.isAfter(beginTime)
                                && receiveTime.isBefore(endTime)) {
                            scoreTaskVO.setReceiveStatus(true);
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 批量删除积分任务
     * @param taskIds
     * @return
     */
    @Override
    public AjaxResult batchDeleteScoreTask(Long[] taskIds) {
        return scoreTaskMapper.batchDeleteScoreTask(taskIds) > 0 ?
                AjaxResult.success("删除积分任务成功") : AjaxResult.error("删除积分任务失败");
    }

    /**
     * 批量领取积分任务奖励
     * @param taskIds
     * @return
     */
    @Override
    public AjaxResult batchGetRewards(Long[] taskIds) {
        Long userId = SecurityUtils.getUserId();
        //查询积分任务记录
        List<ScoreTaskLog> scoreTaskLogs =
                scoreTaskLogMapper.getScoreTaskLogByUserIdAndTaskIds(taskIds,userId);
        //遍历积分任务记录
        for (ScoreTaskLog scoreTaskLog : scoreTaskLogs) {
            LocalDateTime beginTime = LocalDateTime.now().with(LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.now().with(LocalTime.MAX);
            //查询是否已完成
            LocalDateTime finishTime = scoreTaskLog.getFinishTime();
            if (finishTime == null){
                throw new ServiceException("任务id: " + scoreTaskLog.getTaskId()+ " 未完成");
            }
            //如果今天已完成任务
            if (finishTime.isAfter(beginTime)
                    && finishTime.isBefore(endTime)) {
                //查询奖励是否已经领取
                LocalDateTime receiveTime = scoreTaskLog.getReceiveTime();
                //如果领取时间不为空
                if (receiveTime != null){
                    //如果今天已领取
                    if (receiveTime.isAfter(beginTime)
                            && receiveTime.isBefore(endTime)) {
                        throw new ServiceException("积分任务id: "+ scoreTaskLog.getTaskId() + " 奖励已经领取，领取时间：" + scoreTaskLog.getReceiveTime());
                    }
                }
                //发放奖励
                distributeAward(scoreTaskLog.getTaskId());
                //更新积分任务记录
                scoreTaskLog.setReceiveTime(LocalDateTime.now());
                int row = scoreTaskLogMapper.updateScoreTaskLog(scoreTaskLog);
                if (row <= 0){
                    throw new ServiceException("更新积分任务记录失败");
                }
            } else {
                //未完成任务
                throw new ServiceException("任务id: " + scoreTaskLog.getTaskId()+ " 未完成");
            }
        }
        return AjaxResult.success("领取成功");
    }

    /**
     * 发放奖励
     * @param taskId
     */
    public void distributeAward(Long taskId) {
        //查询积分任务
        ScoreTask scoreTask = ScoreTask.builder()
                .id(taskId)
                .build();
        ScoreTask scoreTask1 = scoreTaskMapper.getScoreTask(scoreTask);
        if (scoreTask1 == null){
            throw new ServiceException("任务未找到，id：" +taskId);
        }
        //查询用户信息
        Result<LoginUser> result =
                remoteUserService.getUserInfo(SecurityUtils.getUsername(), SecurityConstants.INNER);
        //如果未找到用户信息
        if (result.getData() == null
                || result.getData().getSysUser() == null){
            throw new ServiceException("未找到用户信息");
        }
        SysUser sysUser = result.getData().getSysUser();
        //发放奖励
        sysUser.setScore(sysUser.getScore() + scoreTask1.getScore());
        Result<Boolean> res =
                remoteUserService.updateUserLoginInfo(sysUser, SecurityConstants.INNER);
        if (res.getData() == null || res.getData() == false){
            throw new ServiceException("更新用户积分失败");
        }
    }
}
